package com.ali.common;

import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class RestTemplateUtil {
    /**
     * Http的Get请求
     */
    public static Map<String, Object> get(String url, Map<String, String> headers) {
        return getResponse(url, null, headers, HttpMethod.GET);
    }

    /**
     * 获取返回信息
     */
    private static Map<String, Object> getResponse(String url, String content, Map<String, String> headers, HttpMethod httpMethod) {
        Map<String, Object> result = new HashMap<>();

        RestTemplate restTemplate = new RestTemplate();

        MultiValueMap<String, String> httpHeaders = new HttpHeaders();

        //设置请求头
        if (headers != null) {
            for (String key : headers.keySet()) {
                httpHeaders.put(key, Collections.singletonList(headers.get(key)));
            }
        }

        URI uri = URI.create(url);

        RequestEntity<String> requestEntity = new RequestEntity<>(content, httpHeaders, httpMethod, uri);

        ParameterizedTypeReference<Object> parameterizedTypeReference = new ParameterizedTypeReference<>() {
        };

        ResponseEntity<Object> responseEntity = restTemplate.exchange(requestEntity, parameterizedTypeReference);

        //获取响应码
        int responseCode = responseEntity.getStatusCode().value();
        result.put("responseCode", responseCode);

        //获取返回参数
        Object response = responseEntity.getBody();
        result.put("response", response);

        //获取返回头
        HttpHeaders responseHeaders = responseEntity.getHeaders();
        for (String key : responseHeaders.keySet()) {
            result.put(key, responseHeaders.get(key));
        }

        return result;
    }

    /**
     * Http的Post请求
     */
    public static Map<String, Object> post(String url, String content, Map<String, String> headers) {
        return getResponse(url, content, headers, HttpMethod.POST);
    }
}